//
//  OrderDetailVC.m
//  KuWoCan
//
//  Created by hwd on 17/3/14.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "OrderDetailVC.h"
#import "CargoCell.h"
#import "orderTotalCell.h"
#import "OrderInfoCell.h"
#import "DispatchInfoCell.h"
#import "ReceiveSucccessVC.h"
#import "NwOrderRequest.h"
#import "OrderDetailModel.h"
#import "OrderCargoChooseVC.h"
#import "BottomDoubleBtnView.h"
#import "OrderPayVC.h"

//Cell
#import "OrderRecordTableViewCell.h"
#import "OrderDetailGiftsTableViewCell.h"

static NSString *const OrderGiftsCellIdentifier = @"OrderDetailGiftsTableViewCell";

@interface OrderDetailVC ()<UITableViewDelegate,UITableViewDataSource>

/**
 商品种类数量
 */
@property (nonatomic,strong)NSMutableArray *cargoListArr;

@property (nonatomic,strong)NSMutableArray *checkListArr;
@property (nonatomic, copy) NSArray<OrderDetailListModel *> *giftsArr;

@property (nonatomic,strong)OrderDetailInfoModel *orderInfoModel;

@property (nonatomic,strong)UITableView *tabView;

@property (nonatomic,strong)UIAlertView *phoneCallAlert;

@property (nonatomic,strong)UIAlertView *deleteAlert;

@end

@implementation OrderDetailVC
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    NwOrderRequest *request = [[NwOrderRequest alloc] init];
    [request startRequestOrdersDetailWithOrderId:_orderId];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            OrderDetailModel *model = [[OrderDetailModel alloc] initWithDictionary:result error:nil];
            self.cargoListArr = [OrderDetailListModel arrayOfModelsFromDictionaries:model.itemList];
            self.checkListArr = [OrderDetailCheckModel arrayOfModelsFromDictionaries:model.recordList];
            _orderInfoModel = model.kwOrder;
            self.giftsArr = model.giftlist;
            [self setUpUI];
            [self createChangeBtn];
        } else {
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}

#pragma mark - Config UI
- (void)setUpUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"订单详情";

    //创建列表
    _tabView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    _tabView.backgroundColor = KwBgColor;
    _tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tabView.estimatedRowHeight = 40.0;
    _tabView.rowHeight = UITableViewAutomaticDimension;
    _tabView.delegate = self;
    _tabView.dataSource = self;
    [self.view addSubview:_tabView];
    [_tabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@10);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@-55);
    }];

    [self createBottomView];
}

- (void)createBottomView
{
    //这里创建底部操作按钮,先要判断是否是本人的订单,如果是在判断自己的身份,显示对应按钮
    //是本人订单
    //根据订单状态来显示底部按钮
    if ([[Singleton shareInstance].userType integerValue] == UserTypeAgency)
    {
        if ([_orderInfoModel.user.id isEqualToString:[Singleton shareInstance].userId])
        {
            if ([_orderStatus integerValue] == OrderQueryStatusToReceive)
            {
                [self createBottomBtnWithTitle:@"确认收货"];
            }
            else if ([_orderStatus integerValue] == OrderQueryStatusToSubmit)
            {
                [self createBottomBtnWithTitle:@"删除"];
            }
            else if([_orderStatus integerValue] == OrderQueryStatusToAudit)
            {
                [self createBottomBtnWithTitle:@"删除"];
            }
            else if ([_orderStatus integerValue] == OrderQueryStatusToPay)
            {
                [self createBottomBtnWithTitle:@"确认支付"];
            }
            else
            {
                [_tabView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(@0);
                }];
            }
        }
    }
    else
    {
        if ([_orderInfoModel.approverUserId isEqualToString:[Singleton shareInstance].userId])
        {
            if([_orderStatus integerValue] == OrderQueryStatusToAudit)
            {
                [self createDoubleBtnsView];
            }
            else if ([_orderStatus integerValue] == OrderQueryStatusAuditting || [_orderStatus integerValue] == OrderQueryStatusAudittingForShippingDepartment)
            {
                [self createDoubleBtnsView];
            }
            else
            {
                [_tabView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(@0);
                }];
            }
        }
        else
        {
            [_tabView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(@0);
            }];
        }
    }
}

- (void)createBottomBtnWithTitle:(NSString *)title
{
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [confirmBtn setBackgroundColor:KwBlueColor];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setTitle:title forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = KwFont(16.0);
    [confirmBtn addTarget:self action:@selector(confirmReceipt) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.layer.masksToBounds = YES;
    confirmBtn.layer.cornerRadius = 5.0;
    [self.view addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-5);
        make.top.equalTo(_tabView.mas_bottom).offset(1);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];
}

- (void)createDoubleBtnsView
{
    //拒绝  通过
    BottomDoubleBtnView *btnsView = [[BottomDoubleBtnView alloc] init];
    btnsView.orderId = _orderId;
    btnsView.orderStatus = _orderStatus;
    btnsView.moduleType = HomeModuleTypeOrder;
    [self.view addSubview:btnsView];
    [btnsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-5);
        make.top.equalTo(_tabView.mas_bottom).offset(1);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];
}

- (UIView *)createHeaderViewWithSection:(NSInteger)section
{
    NSArray *titleArr = @[@"审批信息",@"订单信息",@"配送信息"];
    UIView *headView = [UIView new];
    headView.backgroundColor = [UIColor whiteColor];

    UILabel *checkLab = [UILabel new];
    checkLab.textColor = [UIColor blackColor];
    checkLab.font = [UIFont systemFontOfSize:15];
    checkLab.textAlignment = NSTextAlignmentLeft;
    checkLab.text = titleArr[section-1];
    [headView addSubview:checkLab];
    [checkLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@10);
        make.left.equalTo(@15);
        make.height.equalTo(@15);
    }];

    UIView *lineView = [UIView new];
    lineView.backgroundColor = KwColor(@"#eeeeee");
    [headView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.top.equalTo(checkLab.mas_bottom).offset(10);
        make.height.equalTo(@1.5);
    }];

    return headView;
}

#pragma mark - UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section)
    {
        case 0:
        {
            NSInteger cellCount = 0;
            if (self.cargoListArr.count > 0) {
                cellCount += (self.cargoListArr.count + 1);
            }
            if (self.giftsArr.count > 0) {
                cellCount += self.giftsArr.count;
            }
            return cellCount;
//
//            if (self.cargoListArr.count > 0)
//            {
//                return self.cargoListArr.count+1;
//            }
//            else
//            {
//                return 0;
//            }

        }
            break;
        case 1:
        {
            //待审批,待提交状态下,无审批信息,隐藏
            if (([_orderInfoModel.approvalType isEqualToString:@"0"] || !_orderInfoModel.approvalType) && ([_orderStatus integerValue] == OrderQueryStatusToSubmit || [_orderStatus integerValue] == OrderQueryStatusToAudit))
            {
                return 0;
            }
            else
            {
                if (self.checkListArr.count > 0)
                {
                    return self.checkListArr.count;
                }
                else
                {
                    return 0;
                }
            }
        }
            break;
        case 2:
        {
            return 1;
        }
            break;
        case 3:
        {
            //待收货,已完成状态下,才显示配送信息
            if ([_orderStatus integerValue] == OrderQueryStatusToReceive || [_orderStatus integerValue] == OrderQueryStatusCompleted)
            {
                return 1;
            }
            else
            {
                return 0;
            }

        }
            break;
        default:
            break;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cargoCell_ID = @"CargoCell";
    static NSString *orderTotalCell_ID = @"orderTotalCell";
    static NSString *checkCellID = @"checkCellID";
    static NSString *orderInfoCell_ID = @"OrderInfoCell";
    static NSString *dispatchInfoCell_ID = @"DispatchInfoCell";

    if (indexPath.section == 0)
    {
        if (indexPath.row == self.cargoListArr.count + self.giftsArr.count)
        {
            orderTotalCell *cell;
            //这一行为合计
            cell = [tableView dequeueReusableCellWithIdentifier:orderTotalCell_ID];
            if (!cell)
            {
                cell = [[orderTotalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:orderTotalCell_ID];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.oTotalParaLab.text = [NSString stringWithFormat:@"¥%.2f", [_orderInfoModel.totalPrice floatValue]];
            cell.oNumberLab.text = [NSString stringWithFormat:@"共%ld件商品",[_orderInfoModel.totalBox integerValue]];
            return cell;
        }
        else if (indexPath.row < self.cargoListArr.count)
        {
            CargoCell *cell;
            //其余为商品展示
            cell = [tableView dequeueReusableCellWithIdentifier:cargoCell_ID];
            if (!cell)
            {
                cell = [[CargoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cargoCell_ID];
            }
            if (self.cargoListArr.count > 0 && indexPath.row < self.cargoListArr.count)
            {
                cell.orderModel = self.cargoListArr[indexPath.row];
            }

            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        } else {
            OrderDetailGiftsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:OrderGiftsCellIdentifier];
            if (!cell) {
                cell = [[OrderDetailGiftsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:OrderGiftsCellIdentifier];
            }
            [cell hiddenLabelImage];
            if (indexPath.row == self.cargoListArr.count) {
                [cell showLabelImage];
                [cell setTopBlankHeight:14];
                [cell setBottomBlackHeight:0];
            } else if (indexPath.row == (self.cargoListArr.count + self.giftsArr.count - 1)) {
                [cell setTopBlankHeight:10];
                [cell setBottomBlackHeight:17];
            } else {
                [cell setTopBlankHeight:10];
                [cell setBottomBlackHeight:0];
            }

            [cell config:self.giftsArr[indexPath.row - self.cargoListArr.count]];

            return cell;
        }

    }
    else if(indexPath.section == 1)
    {
        OrderRecordTableViewCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:checkCellID];
        if (!cell) {
            cell = [[OrderRecordTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:checkCellID];
        }
//        [cell configCell:self.checkListArr];
        [cell configCell:self.checkListArr[indexPath.row]];
//        if (self.checkListArr && self.checkListArr.count > 0)
//        {
//            OrderDetailCheckModel *model = self.checkListArr[indexPath.row];
//
//            UILabel *firstLab = [UILabel new];
//            firstLab.textColor = [UIColor grayColor];
//            firstLab.font = [UIFont systemFontOfSize:14.0];
//            firstLab.textAlignment = NSTextAlignmentLeft;
//            firstLab.text = [NSString stringWithFormat:@"%@，%@，%@",model.user.name,model.approverTime,model.approverMemo];
//            [cell addSubview:firstLab];
//            [firstLab mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.equalTo(@15);
//                make.height.equalTo(@25);
//                make.top.equalTo(@10);
//                make.bottom.equalTo(@-15);
//            }];
//        }

//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.section == 2)
    {
        OrderInfoCell *cell;
        //这一行为订单信息
        cell = [tableView dequeueReusableCellWithIdentifier:orderInfoCell_ID];
        if (!cell)
        {
            cell = [[OrderInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:orderInfoCell_ID];
        }
        cell.firLab.text = [NSString stringWithFormat:@"订单编号:%@",_orderInfoModel.orderNumber];
        cell.secLab.text = [NSString stringWithFormat:@"提交时间:%@",_orderInfoModel.createDate];
        cell.thirdLab.text = [NSString stringWithFormat:@"订单备注:%@",_orderInfoModel.orderMemo ?: @""];
        cell.personLab.text = [NSString stringWithFormat:@"收货地址:%@   %@",_orderInfoModel.userName,_orderInfoModel.userPhone];
        cell.addressLab.text = [NSString stringWithFormat:@"                %@",_orderInfoModel.userAddress];
        if (_orderInfoModel.refuseReason && !_orderInfoModel.refuseReason.isEmptyString) {
            cell.refuseLabel.text = [NSString stringWithFormat:@"拒绝原因:%@", _orderInfoModel.refuseReason];
            cell.refuseLabel.numberOfLines = 0;
        }
        return cell;
    }
    else
    {
        DispatchInfoCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:orderInfoCell_ID];
        if (!cell)
        {
            cell = [[DispatchInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:dispatchInfoCell_ID];
        }
        [cell configDriverCellWithDriverName:_orderInfoModel.driverName driverPhone:_orderInfoModel.driverPhone];
        cell.block = ^(){
            _phoneCallAlert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"呼叫:%@",_orderInfoModel.driverPhone?:@"17607192143"] message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [_phoneCallAlert show];
        };

        return cell;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 0.0001;
    }
    else if(section == 1)
    {
        //待审批,待提交状态下,无审批信息,隐藏
        if (([_orderInfoModel.approvalType isEqualToString:@"0"] || !_orderInfoModel.approvalType) && ([_orderStatus integerValue] == OrderQueryStatusToSubmit || [_orderStatus integerValue] == OrderQueryStatusToAudit))
        {
            return 0.0001;
        }
        else
        {
            return 45;
        }

    }
    else if(section == 3)
    {
        //待收货,已完成状态下,才显示配送信息
        if ([_orderStatus integerValue] == OrderQueryStatusToReceive || [_orderStatus integerValue] == OrderQueryStatusCompleted)
        {
            return 45;
        }
        else
        {
            return 0.0001;
        }
    }
    else
    {
        return 45;
    }

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return nil;
    }
    else if(section == 1)
    {
        //待审批,待提交状态下,无审批信息,隐藏
        if (([_orderInfoModel.approvalType isEqualToString:@"0"] || !_orderInfoModel.approvalType) && ([_orderStatus integerValue] == OrderQueryStatusToSubmit || [_orderStatus integerValue] == OrderQueryStatusToAudit))
        {
            return nil;
        }
        else
        {
            return [self createHeaderViewWithSection:section];
        }

    }
    else if(section == 3)
    {
        //待收货,已完成状态下,才显示配送信息
        if ([_orderStatus integerValue] == OrderQueryStatusToReceive || [_orderStatus integerValue] == OrderQueryStatusCompleted)
        {
            return [self createHeaderViewWithSection:section];
        }
        else
        {
            return nil;
        }
    }
    else
    {
        return [self createHeaderViewWithSection:section];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10 * screenW_6;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [UIView new];
    footerView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
    return footerView;
}

#pragma mark - event response
//修改信息
- (void)changeInfo
{
    OrderCargoChooseVC *VC = [[OrderCargoChooseVC alloc] init];
    VC.type = VCTypeChange;
    VC.infoModel = _orderInfoModel;
    VC.cargoListArr = self.cargoListArr;
    VC.orderStatus = _orderStatus;
    VC.orderId = _orderId;
//    if (_ == HomeModuleTypeOA)
////        VC.picArr = _pic
//    }
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)onTapLeftBarButton {
    [Singleton shareInstance].noRefresh = YES;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - private method
//修改按钮,先判断是否是自己的订单
//如果是自己订单,待提交  待审批状态下  有修改按钮
- (void)createChangeBtn
{
    if ([_orderInfoModel.user.id isEqualToString:[Singleton shareInstance].userId])
    {
        if ([[Singleton shareInstance].userType integerValue] == UserTypeAgency)
        {
            if ([_orderStatus integerValue] == OrderQueryStatusToSubmit || [_orderStatus integerValue] == OrderQueryStatusToAudit)
            {
                [self createRightButton:@"修改" selector:@selector(changeInfo)];
            }
        }
    }
}

- (void)confirmReceipt
{

    if ([_orderStatus integerValue] == OrderQueryStatusToReceive)
    {
        [self showSelectViewWithTitle:@"是否确认收货" ActionBlock:^{
            NwOrderRequest *request = [[NwOrderRequest alloc] init];
            [request startRequestPassOrdersWithOrderId:_orderId userId:[Singleton shareInstance].userId orderStatus:[NSString stringWithFormat:@"%ld",(long)OrderQueryStatusToReceive] approvalType:@"0" refuseReason:@"" paymentProof:@""];
            [request completion:^(id result, NSString *message, id extension, BOOL succ) {
                if (succ)
                {
                    //确认收货按钮
                    ReceiveSucccessVC *vc = [[ReceiveSucccessVC alloc] initWithOrderDetailInfoModel:_orderInfoModel];
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }];
        }];
    }
    else if ([_orderStatus integerValue] == OrderQueryStatusToSubmit || [_orderStatus integerValue] == OrderQueryStatusToAudit)
    {
        [self deleteOrder];
    }
    else if ([_orderStatus integerValue] == OrderQueryStatusToPay)
    {
        [self showSelectViewWithTitle:@"是否确认支付" ActionBlock:^{
            //支付
            OrderPayVC *vc = [[OrderPayVC alloc] init];
            vc.orderId = _orderId;
            [self.navigationController pushViewController:vc animated:YES];
        }];
    }
}

- (void)deleteOrder
{
    _deleteAlert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确定删除？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [_deleteAlert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView == _deleteAlert)
    {
        if (buttonIndex == 1)
        {
            //删除
            NwOrderRequest *request = [[NwOrderRequest alloc] init];
            [request startRequestDeleteOrdersWithOrderId:_orderId];
            [request completion:^(id result, NSString *message, id extension, BOOL succ) {
                if (succ)
                {
                    [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }];
        }
    }
    else
    {
        if (buttonIndex == 1)
        {
            NSString *allString = [NSString stringWithFormat:@"tel:%@",_orderInfoModel.driverPhone?:@"17607192143"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:allString]];
        }
    }
}

#pragma mark - PromprtView
- (void)showSelectViewWithTitle:(NSString *)title ActionBlock:(void(^)()) block {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (block) {
            block();
        }
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - getter and setter
- (NSMutableArray *)cargoListArr
{
    if (!_cargoListArr)
    {
        _cargoListArr = [NSMutableArray array];
    }
    return _cargoListArr;
}

- (NSMutableArray *)checkListArr
{
    if (!_checkListArr)
    {
        _checkListArr = [NSMutableArray array];
    }
    return _checkListArr;
}

- (NSArray<OrderDetailListModel *> *)giftsArr {
    if (!_giftsArr) {
        _giftsArr = [NSArray array];
    }
    return _giftsArr;
}

@end
